from flask import Blueprint, Response
from bs4 import BeautifulSoup
import requests
import re
from cache import cache

jsdelivr_base_url = "https://cdn.jsdelivr.net/"
jsdelivr_proxy = Blueprint('jsdelivr_proxy', __name__)

@jsdelivr_proxy.route('/jsdelivr/<path:subpath>')
@cache.memoize(timeout=3600)
def jsdelivr(subpath):
    return proxy_request(jsdelivr_base_url, subpath)

def proxy_request(base_url, subpath):
    # Construct the full URL
    full_url = f"{base_url}{subpath}"

    # Get the content from the target URL
    response = requests.get(full_url, headers={"Accept-Encoding": "identity"})

    # Copy all response headers
    headers = {key: value for key, value in response.headers.items()}

    # Parse HTML content and modify links if the content is HTML
    content = response.content
    if response.headers.get('content-type', '').startswith('text/html'):
        soup = BeautifulSoup(content, 'html.parser')
        for link in soup.find_all('a', href=True):
            href = link['href']
            # If the link is not an absolute URL and not a javascript link
            if not re.match(r'^[a-z]+://', href) and not href.startswith('javascript:'):
                link['href'] = f"/jsdelivr{href}"

        content = str(soup)

    return Response(content, status=response.status_code, headers=headers, content_type=response.headers['content-type'])
